﻿
namespace BackupLib.Remoting
{
    using System;
    using System.Collections;
    using System.Runtime.Remoting;
    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Ipc;
    using System.Security.Principal;

    public class IPCHelper
    {
        public static void RegisterServer()
        {
            //Instantiate our server channel.
            //IpcServerChannel channel = new IpcServerChannel("ServerChannel");
            IDictionary prop = new Hashtable();
            prop["portName"] = "ServerChannel";
            //prop["name"] = String.Empty;    //Ensures Unique name.

            //localisation for authorization "Everyone"
            SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount;
            prop["authorizedGroup"] = account.Value;

            BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider();
            serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
            BinaryClientFormatterSinkProvider clientProv = new BinaryClientFormatterSinkProvider();
            IpcChannel channel = new IpcChannel(prop, clientProv, serverProv);

            //Register the server channel.
            ChannelServices.RegisterChannel(channel, true);

            //Register this service type.
            RemotingConfiguration.RegisterWellKnownServiceType(
                                        typeof(ServerMethods),
                                        "ServerMethods",
                                        WellKnownObjectMode.Singleton);
        }


        public static void RegisterClient()
        {
            //Create an IPC client channel.
            BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider();
            serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
            BinaryClientFormatterSinkProvider clientProv = new BinaryClientFormatterSinkProvider();
            var prop = new Hashtable();
            prop["portName"] = Guid.NewGuid().ToString();
            SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount;
            prop["authorizedGroup"] = account.Value;
            IpcChannel channel = new IpcChannel(prop, clientProv, serverProv);


            //Register the channel with ChannelServices.
            ChannelServices.RegisterChannel(channel, true);

            //Register the client type.
            RemotingConfiguration.RegisterWellKnownClientType(
                typeof(ServerMethods),
                "ipc://ServerChannel/ServerMethods");
        }
    }
}
